package com.byd.model;

import java.lang.ref.WeakReference;
import com.byd.application.MyApplication;
import com.byd.utils.Lg;

public class DataManager {
	private static WeakReference<DataManager> sWeakDataManager;
	private NotificationManager mNotificationManager;
	private DataManager() {
		EventBus.init();
		Lg.init(MyApplication.getInstance());
	}

	public static DataManager getInstance() {
		DataManager manager = null;
		if(sWeakDataManager == null || (manager = sWeakDataManager.get()) == null) {
			manager = new DataManager();
			sWeakDataManager = new WeakReference<DataManager>(manager);
		}
		return manager;
	}

	public static DataManager check() {
		if(sWeakDataManager != null) {
			return sWeakDataManager.get();
		}
		return null;
	}

	public void holdOn(int time) {
		MyThreadPool.postNewThread("holdOn", new HoldOnThread(this, time));
	}

	private static class HoldOnThread implements Runnable {
		DataManager manager;
		long time;

		public HoldOnThread(DataManager manager, int time) {
			this.manager = manager;
			this.time = time;
		}

		@Override
		public void run() {
			try {
				Thread.sleep(time);
				if(manager != null) {
					Lg.i("hold on finish");
				}
				manager = null;
				if(MyApplication.getLastActivity() == null) {
					MyApplication.callGc(500, 2, 250);
				}
			}
			catch (final Exception e) {
				Lg.printStackTrace(e);
			}
		}
	}

	@Override
	protected void finalize() throws Throwable {
		Lg.i("finalize: " + toString());
		try {
			MyThreadPool.release();
		}
		catch (final Exception e) {
			Lg.printStackTrace(e);
		}
		try {
			EventBus.release();
		}
		catch (final Exception e) {
			Lg.printStackTrace(e);
		}
		try {
			Lg.release();
		}
		catch (final Exception e) {
			Lg.printStackTrace(e);
		}
		super.finalize();
	}

	public synchronized NotificationManager getNotificationManager() {
		if(mNotificationManager == null) {
			mNotificationManager = new NotificationManager(MyApplication.getInstance());
		}
		return mNotificationManager;
	}
}
